<template>
  <div class="container">
    <div class="apply-container">
      <div class="apply-container-head"></div>
      <div class="apply-container-body">
        <div class="apply-container-body-title">
          <div class="apply-container-body-title-font">添加用户</div>
          <div class="apply-container-body-title-return">
            <el-button size="small" @click="goBackPage">返回</el-button>
          </div>
        </div>
        <el-divider class="apply-container-body-title-line"></el-divider>
        <div class="apply-container-body-content">
          <el-form :model="User" label-width="100px" label-position="LabelPosition" ref="User" :rules="UserRules"
            style="width: 100%;">
            <el-form-item label="工号:" prop="InputUserId" style="width: 40%;">
              <el-input v-model="User.InputUserId" placeholder="请输入工号" clearable></el-input>
            </el-form-item>
            <el-form-item label="身份证上传" prop="IdCard" style="width: 55%; text-align: left;">
              <el-upload v-model="User.IdCard" class="upload-demo " action="http://localhost:8088/idUpLoad"
                accept=".png, .jpg" :on-success="IdCardGetUrl" :on-preview="handlePreview" :on-remove="handleRemove"
                :before-remove="beforeRemove" :limit="1" :on-exceed="handleExceed">
                <el-button size="small" type="primary">点击上传</el-button>
                <span slot="tip" class="el-upload__tip width" style="margin-left: 10px;">（只能上传png/jpg文件，且不超过10M）</span>
              </el-upload>
            </el-form-item>
            <el-form-item label="姓名:" prop="InputUserName" style="width: 40%;">
              <el-input v-model="User.InputUserName" placeholder="请输入姓名" :disabled="true" clearable></el-input>
            </el-form-item>
            <el-form-item label="身份证号:" prop="InputUserIdNumber" style="width: 40%;">
              <el-input v-model="User.InputUserIdNumber" placeholder="请输入身份证号" :disabled="true" clearable></el-input>
            </el-form-item>
            <el-form-item label="电话:" prop="InputUserPhone" style="width: 40%;">
              <el-input v-model="User.InputUserPhone" placeholder="请输入电话" clearable></el-input>
            </el-form-item>
            <el-form-item label="年龄:" prop="InputUserAge" style="width: 40%;">
              <el-input v-model="User.InputUserAge" placeholder="请输入年龄" :disabled="true" clearable></el-input>
            </el-form-item>
            <el-form-item label="职位:" prop="InputUserPosition" style="width: 40%;">
              <el-input v-model="User.InputUserPosition" placeholder="请输入职位" clearable></el-input>
            </el-form-item>
            <el-form-item label="所属部门:" prop="SelectUserDepartment" style="width: 40%;">
              <el-select v-model="User.SelectUserDepartment" placeholder="请选择所属部门" clearable>
                <el-option label="销售部" value="销售部"></el-option>
                <el-option label="财务部" value="财务部"></el-option>
                <el-option label="市场部" value="市场部"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="角色:" prop="CheckboxRole" style="width: 55%;">
              <el-checkbox-group v-model="User.CheckboxRole">
                <el-checkbox :label="role.roleName" v-for="role in roleList" :key="role.roleName"></el-checkbox>
              </el-checkbox-group>
            </el-form-item>

            <div class="apply-container-body-content-submit">
              <el-button @click="doAdd('User')" type="primary">提交</el-button>
            </div>
          </el-form>
        </div>
      </div>
      <div class="apply-container-footer"></div>
    </div>
  </div>
</template>

<script>
import { addUser, addUserRole, getAllRoles } from "../../api/user"
export default {
  name: 'AddUserView',
  data() {
    return {
      LabelPosition: 'right',
      User: {
        InputUserId: null,
        InputUserName: null,
        InputUserIdNumber: null,
        InputUserPhone: null,
        InputUserAge: null,
        InputUserPosition: null,
        SelectUserDepartment: null,
        CheckboxRole: [],
        IdCard: null,
      },
      UserRules: {
        InputUserId: [
          { required: true, message: '请输入工号', trigger: 'blur' },
          { min: 8, max: 8, message: '长度为8个字符', trigger: 'blur' }
        ],
        InputUserName: [{ required: true, message: '请输入姓名', trigger: 'blur' },],
        InputUserIdNumber: [
          { required: true, message: '请输入身份证号', trigger: 'blur' },
          { min: 18, max: 18, message: '请输入正确的18位身份证号', trigger: 'blur' }
        ],
        InputUserPhone: [
          { required: true, message: '请输入电话', trigger: 'blur' },
          { min: 11, max: 11, message: '请输入正确的11位手机号', trigger: 'blur' }
        ],
        InputUserAge: [{ required: true, message: '请输入年龄', trigger: 'blur' },],
        InputUserPosition: [{ required: true, message: '请选择职位', trigger: 'blur' },],
        SelectUserDepartment: [{ required: true, message: '请选择所属部门', trigger: 'change' },],
        CheckboxRole: [{ required: true, message: '请选择至少一位角色', trigger: 'change' },],
        IdCard: { required: true, message: '请上传身份证', trigger: 'change' },
      },
      userTableAdd: {
        userName: null,
        userId: null,
        userIdNumber: null,
        userPhone: null,
        userAge: null,
        userPosition: null,
        userDepartment: null,
        userPassword: null,
      },
      SubmitCode: [],
      userRoleAdd: [],
      roleList: [],
    }
  },

  methods: {
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePreview(file) {
      console.log(file);
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
    },
    async beforeRemove(file) {
      await this.$confirm(`确定移除 ${file.name}?`);
      this.User.IdCard = null;
      this.User.InputUserName = null;
      this.User.InputUserIdNumber = null;
      this.User.InputUserAge = null;
    },
    IdCardGetUrl(response) {
      this.User.IdCard = "idcard.jpg"
      this.User.InputUserName = response.data[0];
      this.User.InputUserIdNumber = response.data[1];
      this.User.InputUserAge = response.data[2];
      this.$message({
        message: "身份证上传成功",
        duration: 2000,
        showClose: true,
        type: 'success'
      });
    },
    goBackPage() {
      this.$router.go(-1)
    },
    doAddUser() {
      return new Promise((resolve, reject) => {
        this.userTableAdd.userName = this.User.InputUserName
        this.userTableAdd.userId = this.User.InputUserId
        this.userTableAdd.userAge = this.User.InputUserAge
        this.userTableAdd.userIdNumber = this.User.InputUserIdNumber
        this.userTableAdd.userPhone = this.User.InputUserPhone
        this.userTableAdd.userDepartment = this.User.SelectUserDepartment
        this.userTableAdd.userPosition = this.User.InputUserPosition
        this.userTableAdd.userPassword = 'uHrL6Rcoi9CSruRc-abpRQ=='

        addUser(this.userTableAdd).then(res => {
          this.SubmitCode.push(res.data.code);
          if (res.data.code === '0') {
            console.log(res.data.code);
            resolve(); // 表示异步操作成功
          } else {
            console.log(res.data.msg);
            reject(res.data.msg); // 表示异步操作失败
          }
        })
      });
    },
    doAddUserRole() {
      return new Promise((resolve, reject) => {

        for (let i = 0; i < this.User.CheckboxRole.length; i++) {
          let newItem = {
            userId: this.User.InputUserId,
            userRole: this.User.CheckboxRole[i]
          };
          this.userRoleAdd.push(newItem)
        }
        console.log(this.userRoleAdd)

        addUserRole(this.userRoleAdd).then(res => {
          this.SubmitCode.push(res.data.code);
          if (res.data.code === '0') {
            console.log(res.data.code);
            resolve(); // 表示异步操作成功
          } else {
            console.log(res.data.msg);
            reject(res.data.msg); // 表示异步操作失败
          }
        })
      });
    },
    doAdd(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$confirm('此操作将新增该用户并将这些角色赋予这个用户, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {

            this.doAddUser()
              .then(() => this.doAddUserRole())
              .then(() => {
                this.JudgeSuccess(this.SubmitCode);
              })
              .catch(error => {
                console.log(error);
                this.$message.error('提交失败: ' + error);
              });

          }).catch(() => {
            this.$message({
              type: 'info',
              message: '已取消'
            });
          });
        }
        else {
          return false;
        }
      })
    },
    JudgeSuccess(data) {
      if (this.JudgeSubmitCode(data)) {
        this.showMessage('添加成功', 'success');
        this.goBackPage();
      } else
        this.showMessage('添加失败', 'error');
    },
    JudgeSubmitCode(data) {
      const allZeros = data.every(code => code === '0');
      return allZeros;
    },
    showMessage(message, type) {
      this.$message({
        message: message,
        duration: 2000,
        showClose: true,
        type: type,
      });
    },
  },

  mounted() {
    getAllRoles().then(res => {
      this.roleList = res.data.data
    })
  },
}
</script>

<style scoped>
.container {
  /* height: 100%; */
  width: 95%;
  margin: 0 auto;
  margin-top: 1%;
  background-color: #ffffff;
}

.apply-container {
  width: 100%;
  height: 100%;
  margin: 0 auto;
  /* background-color: #f2f2f2; */
}

.apply-container-head {
  width: 95%;
  height: 30px;
  margin: 0 auto;
}

.apply-container-body {
  width: 95%;
  height: 92%;
  margin: 0 auto;
  background-color: #ffffff;

}

.apply-container-body-title {
  width: 98%;
  height: 5%;
  margin: 0 auto;
  display: flex;
}

.apply-container-body-title-return {
  width: 100%;
  padding-top: 5px;
  display: flex;
  justify-content: flex-end;
}

.apply-container-body-title-line {
  height: 1px;
  width: 98%;
  margin: 5px auto;
}

.apply-container-body-title-font {
  width: 100%;
  height: 99%;
  font-size: 18px;
  font-weight: bold;
  text-align: left;
  padding-top: 10px;
}

.apply-container-body-content {
  width: 85%;
  height: 100%;
  margin: 20px auto;
  display: flex;

}

.apply-container-body-content-submit {
  width: 100%;
  height: 40px;
  display: flex;
  justify-content: flex-end;
  margin-bottom: 20px;
}

.apply-container-footer {
  width: 95%;
  height: 50px;
  margin: 0 auto;
}
</style>